using System.Drawing;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealthBar : MonoBehaviour
{
    [SerializeField] private GameObject healthSlider;        // 直接拖屏幕UI上的 Image
    [SerializeField] private DataController dataController; // 直接拖角色上的 DataController
    public GameObject healthGameObject;

    void Awake()
    {
        if (healthSlider == null)
        {

        }
;
    }

    void OnEnable()
    {
        if (dataController) dataController.upDateHealthBar += UpdateHpBar;
        if (!dataController) dataController = FindObjectOfType<DataController>(); // 兜底
    }

    void OnDisable()
    {
        if (dataController) dataController.upDateHealthBar -= UpdateHpBar;
    }

    private void UpdateHpBar(int currentHealth, int maxHealth)
    {
        if (healthSlider == null) return;
        setHealth(currentHealth);
    }
    public void setHealth(int currentHealth)
    {
        Transform parent = healthGameObject.transform; // 获取父节点
        foreach (Transform child in parent)
        {
            Destroy(child.gameObject); // 销毁子节点
        }
        for (int i = 0; i < currentHealth; i++)
        {
            GameObject healthPrefab = Instantiate(healthSlider, healthGameObject.transform.position, Quaternion.identity, transform);
            healthPrefab.transform.position = new Vector2(0, 0);
            healthPrefab.transform.parent = healthGameObject.transform;
        }
    }
}
